service.factory('orderFactory',['$q','appFactory',function($q,appFactory){

    var Order = AV.Object.extend('Order');

    var Mission = AV.Object.extend('Mission');

    var MissionFlow = AV.Object.extend('MissionFlow');

    //外卖订单的类型;
    var OUT_ORDER_TYPE = [6,8];

    //售后订单的类型;
    var RETURN_ORDER_TYPE = [11,12];

    //进行中任务的状态码
    var MISSION_PROCESS_STATUS = 1;

    //派送流水的正常状态码
    var MISSION_FLOW_NORMAL = 1;

    //已完成的任务的状态码
    var MISSION_FINISH_STATUS = 0;

    //待同步的状态码
    var TO_SYNC_STATUS = 1;

    //订单的字段信息;
    var ORDER_FIELDS = ['remark','payway','uid','address','messioned','orderid','total','paytime','approvaldate','type','finalAmount','description','areaId','shopId','status','goods','location'];

    //列表需要的状态码
    var ORDER_STATUS = [2500,3000,4000];

    //售后订单列表需要的状态码
    var RETURNORDER_STATUS = [3000,4000];

    //订单结束的状态码
    var ORDER_FINISH_STATUS = 9000;

    var get0Time = function(){
        var today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        today.setMilliseconds(0);
        return today.getTime()/1000;
    }

    var getNext0Time = function(){
        return get0Time() + 60 * 60 * 24;
    }

    return {
        PAGE_SIZE:20,
        getOutOrderList:function(options){

            var todayZeroTime = get0Time();
            var tomZeroTime = todayZeroTime + 60 * 60 * 24;

            var myOrder = new AV.Query(Order);
            myOrder.select(ORDER_FIELDS);
            myOrder.limit(this.PAGE_SIZE);
            myOrder.containedIn('status',ORDER_STATUS);
            myOrder.containedIn('type',OUT_ORDER_TYPE);
            myOrder.containedIn('areaId',options.areaId);
            myOrder.notEqualTo('messioned',true);
            myOrder.addDescending('status');
            myOrder.addAscending('paytime');

            var normalOrder = new AV.Query(Order);
            normalOrder.select(ORDER_FIELDS);
            normalOrder.limit(this.PAGE_SIZE);
            normalOrder.containedIn('status',ORDER_STATUS);
            normalOrder.containedIn('type',OUT_ORDER_TYPE);
            normalOrder.containedIn('areaId',options.areaId);
            normalOrder.notEqualTo('messioned',true);
            normalOrder.addDescending('status');
            normalOrder.addAscending('paytime');

            var monthOrder = new AV.Query(Order);
            monthOrder.select(ORDER_FIELDS);
            monthOrder.limit(this.PAGE_SIZE);
            monthOrder.containedIn('status',ORDER_STATUS);
            monthOrder.containedIn('type',[7]);
            monthOrder.lessThan('bookdate',''+tomZeroTime);//小于第二天
            monthOrder.greaterThan('bookdate',''+todayZeroTime);//大于凌晨
            monthOrder.notEqualTo('messioned',true);
            monthOrder.containedIn('areaId',options.areaId);
            monthOrder.addDescending('status');
            monthOrder.addAscending('paytime');

            var query = AV.Query.or(myOrder,normalOrder, monthOrder);
            return query.find();
        },

        getReturnOrderList:function(options){

            var todayZeroTime = get0Time();
            var tomZeroTime = todayZeroTime + 60 * 60 * 24;

            var myOrder = new AV.Query(Order);
            myOrder.select(ORDER_FIELDS);
            myOrder.limit(this.PAGE_SIZE);
            myOrder.containedIn('status',RETURNORDER_STATUS);
            myOrder.containedIn('type',RETURN_ORDER_TYPE);
            myOrder.containedIn('areaId',options.areaId);
            myOrder.notEqualTo('messioned',true);
            myOrder.addDescending('status');
            myOrder.addAscending('paytime');

            var normalOrder = new AV.Query(Order);
            normalOrder.select(ORDER_FIELDS);
            normalOrder.limit(this.PAGE_SIZE);
            normalOrder.containedIn('status',RETURNORDER_STATUS);
            normalOrder.containedIn('type',RETURN_ORDER_TYPE);
            normalOrder.containedIn('areaId',options.areaId);
            normalOrder.notEqualTo('messioned',true);
            normalOrder.addDescending('status');
            normalOrder.addAscending('paytime');

            var monthOrder = new AV.Query(Order);
            monthOrder.select(ORDER_FIELDS);
            monthOrder.limit(this.PAGE_SIZE);
            monthOrder.containedIn('status',RETURNORDER_STATUS);
            monthOrder.containedIn('type',RETURN_ORDER_TYPE);
            monthOrder.lessThan('bookdate',''+tomZeroTime);//小于第二天
            monthOrder.greaterThan('bookdate',''+todayZeroTime);//大于凌晨
            monthOrder.containedIn('areaId',options.areaId);
            monthOrder.notEqualTo('messioned',true);
            monthOrder.addDescending('status');
            monthOrder.addAscending('paytime');

            var query = AV.Query.or(myOrder,normalOrder, monthOrder);
            return query.find();
        },

        rushMession:function(o){
            var q = $q.defer();
            async.waterfall([
                function(cb){
                    //查询订单状态
                    var query = new AV.Query(Order);
                    query.get(o.id).then(function(res){
                        if(res.get('messioned')===true){
                            cb({error:'手慢拉!~刷新一下再试试!'})
                        }else{
                            //更新订单状态
                            //o.set('status',RUSH_ORDER_STATUS);
                            o.set('rushTime',new Date());
                            o.set('messioned',true);
                            o.set('messionedUser',''+appFactory.getUserInfo().uid);
                            if(res.get('type')===9){
                                o.set('status',7000);
                            }
                            o.save().then(function(res){
                                cb(null,res);
                            }).catch(function(err){
                                cb(err);
                            });
                        }
                    }).catch(function(err){
                        cb({error:'手慢拉!~刷新一下再试试!'})
                    });
                },
                function(arg0,cb){
                    var m = new Mission();
                    var detail = o.attributes;
                    detail['createdAt'] = o.getCreatedAt();
                    m.save({
                        orderid: o.get('orderid'),
                        uid: ''+appFactory.getUserInfo().uid,
                        status: 1,
                        detail: detail,
                        rushTime: new Date()
                    }).then(function(res){
                        cb(null,res);
                    }).catch(function(err){
                        //重置订单的状态
                        o.remove('messioned');
                        o.save().then(function(res){
                            cb(null,res);
                        }).catch(function(err){
                            cb(err);
                        });
                    });
                }
            ],function(err,res){
                if(err){
                    q.reject({error:'手慢拉!~刷新一下再试试!'});
                }else{
                    q.resolve(res);
                }

            });
            return q.promise;

        },

        rushReturnMession:function(o){
            var q = $q.defer();
            async.waterfall([
                function(cb){
                    //查询订单状态
                    var query = new AV.Query(Order);
                    query.get(o.id).then(function(res){
                        if(res.get('messioned')===true){
                            cb({error:'手慢拉!~刷新一下再试试!'})
                        }else{
                            //更新订单状态
                            //o.set('status',RUSH_ORDER_STATUS);
                            o.set('rushTime',new Date());
                            o.set('messioned',true);
                            o.set('messionedUser',''+appFactory.getUserInfo().uid);
                            o.set('status',7000);
                            o.set('syncStatus',2);
                            o.save().then(function(res){
                                cb(null,res);
                            }).catch(function(err){
                                cb(err);
                            });
                        }
                    }).catch(function(err){
                        cb({error:'手慢拉!~刷新一下再试试!'})
                    });
                },
                function(arg0,cb){
                    var m = new Mission();
                    var detail = o.attributes;
                    detail['createdAt'] = o.getCreatedAt();
                    m.save({
                        orderid: o.get('orderid'),
                        uid: ''+appFactory.getUserInfo().uid,
                        status: 1,
                        detail: detail,
                        rushTime: new Date()
                    }).then(function(res){
                        cb(null,res);
                    }).catch(function(err){
                        //重置订单的状态
                        o.remove('messioned');
                        if(res.get('type')===11){
                            o.set('status',3000);
                        }
                        if(res.get('type')===12){
                            o.set('status',4000);
                        }
                        o.save().then(function(res){
                            cb(null,res);
                        }).catch(function(err){
                            cb(err);
                        });
                    });
                }
            ],function(err,res){
                if(err){
                    q.reject({error:'手慢拉!~刷新一下再试试!'});
                }else{
                    q.resolve(res);
                }

            });
            return q.promise;

        },

        //完成订单
        finishOrder:function(oid,operaterId){
            var q = $q.defer();
            async.parallel([
                    function(cb){
                        //完成任务
                        var missionQuery = new AV.Query(Mission);
                        //订单编码
                        missionQuery.equalTo('orderid',oid);
                        //任务状态为进行中
                        missionQuery.equalTo('status',MISSION_PROCESS_STATUS);

                        missionQuery.first().then(function(mission){
                            if(!mission){
                                cb(null,'该订单未查找到任何派送信息!');
                                return;
                            }
                            mission.set('status',MISSION_FINISH_STATUS);
                            mission.set('syncStatus',TO_SYNC_STATUS);
                            //标记为手动结束
                            mission.set('manualFlag',true);
                            mission.set('operaterId',operaterId);
                            mission.set('closeTime',new Date().getTime());
                            mission.save().then(function(){
                                // add mission flow
                                var detail = mission.get('detail');
                                var missionFlow = new MissionFlow();
                                missionFlow.set('uid',mission.get('uid'));
                                missionFlow.set('orderId',oid);
                                missionFlow.set('syncStatus',TO_SYNC_STATUS);
                                missionFlow.set('status',MISSION_FLOW_NORMAL);
                                missionFlow.set('psRebate',detail.psRebate || 1);
                                missionFlow.set('realAccount',(detail.payway == '货到付款')?(''+detail.finalAmount):"0");
                                missionFlow.set('address',detail.address);
                                missionFlow.set('startTime',new Date());
                                missionFlow.set('endTime',new Date());
                                //标记为手动结束
                                missionFlow.set('manualFlag',true);
                                missionFlow.set('operaterId',operaterId);
                                missionFlow.set('closeTime',new Date().getTime());
                                missionFlow.save().then(function(){
                                    cb(null,false);
                                }).catch(function(err){
                                    cb(err);
                                })

                            }).catch(function(err){
                                cb(err)
                            });
                        }).catch(function(err){
                            cb(err)
                        });
                    },
                    function(arg0,cb){
                        if(arg0){
                            if(!confirm(arg0 + '\n是否继续手动完成订单?')){
                                cb(null);
                                return;
                            }
                        }
                        var orderQuery = new AV.Query(Order);
                        orderQuery.equalTo('orderid',oid);
                        orderQuery.first().then(function(order){
                            if(!order){
                                cb('系统中未查找该订单信息,请自己核对!');
                                return;
                            }
                            //标记为手动结束
                            order.set('manualFlag',true);
                            order.set('operaterId',operaterId);
                            order.set('closeTime',new Date().getTime());
                            order.set('status',ORDER_FINISH_STATUS);
                            order.set('syncStatus',2); //将云端代码状态变更为2，更新
                            order.save().then(function(){
                                cb(null);
                            }).catch(function(err){
                                cb(err)
                            });
                        }).catch(function(err){
                            cb(err)
                        });
                    }
                ],
                function(err,res){
                    if(err){
                        q.reject(err);
                    }else{
                        q.resolve(res);
                    }
            });

            return q.promise;
        }
    }
}]);